'use client';

import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import {
  CheckCircleIcon,
  ExclamationCircleIcon,
  XCircleIcon,
  InformationCircleIcon,
} from '@heroicons/react/24/solid';
import { useTimeout, useUnmount } from 'ahooks';

export interface AlertProps {
  className?: string;
  type: 'success' | 'error' | 'warning' | 'info';
  message: string;
  /**
   * The duration in milliseconds before the alert is automatically closed.
   * @default 3000
   */
  duration?: number;
  onClose?: () => void;
}

function AlertNoMemoized(props: AlertProps) {
  const { className, type, message, duration = 3000, onClose } = props;

  const [visible, setVisible] = useState(true);

  const clearTimeout = useTimeout(() => {
    setVisible(false);
    onClose?.();
  }, duration);

  useEffect(() => {
    // If duration is 0, allways show the alert
    if (duration === 0) {
      clearTimeout();
      setVisible(true);
    }
  }, [clearTimeout, duration]);

  useUnmount(() => {
    clearTimeout();
  });

  if (!visible) {
    return null;
  }

  return (
    <div
      role="alert"
      className={clsx(
        'fixed top-5 alert',
        {
          'alert-success': type === 'success',
          'alert-error': type === 'error',
          'alert-warning': type === 'warning',
          'alert-info': type === 'info',
        },
        className
      )}
    >
      {type === 'success' && <CheckCircleIcon className="size-6 text-white" />}
      {type === 'error' && <XCircleIcon className="size-6 text-white" />}
      {type === 'warning' && <ExclamationCircleIcon className="size-6 text-white" />}
      {type === 'info' && <InformationCircleIcon className="size-6 text-white" />}
      <span className="text-white">{message}</span>
    </div>
  );
}

export const Alert = React.memo(AlertNoMemoized);
